# -*- coding: utf-8 -*-
"""
@Time   : 2019/11/21 17:56
@Author : LeeCQ
"""

import time
import os
import re
import asyncio
import requests
from HTTP.Downloader1024.common.functions import getHtml

album = './photos/'
header = {'User-Agent': 'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.6) Gecko/20091201 Firefox/3.5.6'}


async def get_a_photo(photo_url, album_name):
    """

    :param photo_url:
    :param album_name:
    :return:
    """
    local_photo_path = f'{album}/{album_name}/{photo_url[-12:]}'
    if os.path.exists(local_photo_path):
        return 1, local_photo_path
    try:
        print(f'开始下载：{photo_url}')
        _a = await requests.get(photo_url, headers=header).content
        open(local_photo_path, 'wb').write(_a)
        return 0, local_photo_path
    except:
        print('Error')
        return -1, local_photo_path


def get_album(album_url):
    """
    获取相册的全部内容； name - photos
    :param album_url:
    :return:
    """

    head, page = getHtml(album_url, headers=header)
    # album_name = re.findall(r'<title>(.*?)</title>', page)[0]
    # album_name = album_name[:album_name.find('|')]
    album_name = re.findall(r'<span id="subject_tpc">(.*?)</span>', page)[0]
    listURL = re.findall(r'<img src="(.*?)" border="0"', page)
    print(album_name, listURL)

    tasks = [asyncio.ensure_future(get_a_photo(p, album_name)) for p in listURL]
    loop = asyncio.get_event_loop()
    loop.run_until_complete(asyncio.wait(tasks))
    """
    if return_code == 0:
        print(f'{_path} 下载成功')
    elif return_code == 1:
        print(f'{_path} 已经存在')
    elif return_code == -1:
        print(f'{_path} 下载失败。')"""


def main(_url):
    start = time.time()
    get_album(_url)
    print(f'运行时间：{time.time()-start}')

if __name__ == '__main__':
    url = 'http://q1.fnmdsbb.xyz/pw/html_data/114/1911/4441681.html'
    main(url)
